package com.only4play.importapt.service.impl;

import com.only4play.importapt.model.entity.CustomerEntity;
import com.only4play.importapt.service.AbstractMergeRequestService;
import com.only4play.importapt.service.CustomerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class CustomerWrapBatchServiceImpl extends AbstractMergeRequestService {

    @Autowired
    private CustomerService customerService;


    @Override
    protected Object noneMergeAndSingleExecute(WrapRequest request) {
        String userId = request.getUserId();
        return customerService.getById(userId);
    }

    @Override
    protected Object mergeRequestAndExecute(List<AbstractMergeRequestService.WrapRequest> list) {
        List<String> ids = list.stream().map(WrapRequest::getUserId).toList();
        List<CustomerEntity> entities = customerService.listByIds(ids);

        Map<String, CustomerEntity> entityMap = entities.stream()
            .collect(Collectors.toMap(CustomerEntity::getId, item -> item, (a, b) -> a));


        HashMap<String, CustomerEntity> result = new HashMap<>();
        list.forEach(item -> {
            CustomerEntity entity = entityMap.getOrDefault(item.getUserId(), null);
            result.put(item.getRequestId(), entity);
        });

        return result;
    }

    @Override
    protected void splitResponse(List<WrapRequest> requests, Object response) {
        HashMap<String, CustomerEntity> entityMap = (HashMap<String, CustomerEntity>) response;

        requests.forEach(request -> {
            CustomerEntity entity = entityMap.getOrDefault(request.getRequestId(), null);
            request.getFuture().complete(entity);
        });
    }
}
